package cn.cyh.queue_service.websocket;

import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * 叫号大屏WebSocket处理器
 */
// 注释掉@Component以避免Bean定义冲突
// @Component
@Slf4j
public class CallScreenWebSocketHandler extends TextWebSocketHandler {

    /**
     * 存储所有连接的会话
     */
    private static final Map<String, WebSocketSession> SESSIONS = new ConcurrentHashMap<>();


    /**
     * 处理连接建立
     */
    @Override
    public void afterConnectionEstablished(WebSocketSession session) {
        log.info("叫号大屏连接已建立: {}", session.getId());
        SESSIONS.put(session.getId(), session);
        // 解析业务类型ID
        log.info("客户端已订阅业务类型 {}", session.getId());
        SocketMsg msg = new SocketMsg();
        msg.setType("connect");
        msg.setData(session.getId());
        CurrentScreens.broadcastMessage(session, JSONUtil.toJsonStr(msg));
        CurrentScreens.sessionMap.put(session.getId(), session);
    }

    /**
     * 处理消息
     */
    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) {
        log.debug("收到消息: {}", message.getPayload());
    }

    /**
     * 处理连接关闭
     */
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) {
        log.info("叫号大屏连接已关闭: {}, 状态: {}", session.getId(), status);
        SESSIONS.remove(session.getId());
    }

    /**
     * 处理传输错误
     */
    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) {
        log.error("叫号大屏传输错误: {}", exception.getMessage(), exception);

        try {
            session.close(CloseStatus.SERVER_ERROR);
        } catch (IOException e) {
            log.error("关闭会话时发生错误: {}", e.getMessage(), e);
        }
    }

    /**
     * 广播叫号消息给所有客户端
     */
    public void broadcastCallMessage(CallMessage message) {
        String payload = JSONUtil.toJsonStr(message);
        broadcastMessage(payload);
    }

    /**
     * 广播消息给所有客户端
     */
    private void broadcastMessage(String message) {
        SESSIONS.values().forEach(session -> {
            try {
                if (session.isOpen()) {
                    session.sendMessage(new TextMessage(message));
                }
            } catch (IOException e) {
                log.error("发送消息时发生错误: {}", e.getMessage(), e);
            }
        });
    }


    /**
     * 从会话中获取区域ID
     */
    private String getAreaId(WebSocketSession session) {
        Map<String, Object> attributes = session.getAttributes();
        return (String) attributes.getOrDefault("areaId", null);
    }
} 